package com.yituo.mjworld.mvc.dao;

import com.yituo.mjworld.core.utils.BaseDao;
import com.yituo.mjworld.mvc.entity.web.WebOrder;
import org.springframework.stereotype.Repository;

import java.math.BigInteger;
import java.util.List;

@Repository
public class OrderDao extends BaseDao<WebOrder> {

  /**
   * 通过UserId和OrderId 获取指定的订单
   *
   * @return 获取成功返回对应的订单对象, 订单不存在返回null
   */
  public WebOrder getOrderByUserIdAndOrderId(String userId, String orderId) {
    List<WebOrder> list = getSession()
        .createQuery("from WebOrder where userId=:userId and orderId=:orderId")
        .setParameter("userId", userId)
        .setParameter("orderId", orderId)
        .list();
    WebOrder order = null;
    if (list != null && list.size() > 0) {
      order = list.get(0);
    }
    return order;
  }

  /**
   * 通过物流ID和用户ID获取订单列表
   *
   * @param userId
   * @param transportId
   * @return
   */
  public List<WebOrder> getOrdersByUserIdAndTransportId(String userId, String transportId) {
    String hql = "from WebOrder where userId=:userId and transportId=:transportId";
    List<WebOrder> list = getSession()
        .createNativeQuery(hql)
        .setParameter("userId", userId)
        .setParameter("transportId", transportId)
        .list();
    return list;
  }

  /**
   * 更新订单状态
   *
   * @param transactionId
   * @param status
   * @return
   */
  public int updateOrderStatus(String transactionId, int status) {
    String sql = "update web_order set orderStatus=:orderStatus where transactionId=:transactionId";
    int i = getSession()
        .createNativeQuery(sql)
        .setParameter("orderStatus", status)
        .setParameter("transactionId", transactionId).executeUpdate();
    return i;
  }

  /**
   * @param transactionId
   * @return
   */
  public int getOrdersNum(String transactionId) {
    String sql = "select count(id) from web_order where transactionId=:transactionId";
    BigInteger i = (BigInteger) getSession()
        .createNativeQuery(sql)
        .setParameter("transactionId", transactionId).uniqueResult();
    return i.intValue();
  }
}
